package com.buaa.divinationmaster.core.database;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.buaa.divinationmaster.core.database.dao.DivinationHistoryDao;
import com.buaa.divinationmaster.core.database.dao.HexagramDao;
import com.buaa.divinationmaster.core.database.dao.LenormandCardDao;
import com.buaa.divinationmaster.core.database.dao.TarotCardDao;
import com.buaa.divinationmaster.core.database.dao.YaoTextDao;
import com.buaa.divinationmaster.core.database.entities.DivinationHistory;
import com.buaa.divinationmaster.core.database.entities.Hexagram;
import com.buaa.divinationmaster.core.database.entities.LenormandCard;
import com.buaa.divinationmaster.core.database.entities.TarotCard;
import com.buaa.divinationmaster.core.database.entities.YaoText;
import com.buaa.divinationmaster.shared.data.repository.DataInitializer;

/**
 * 占卜大师应用主数据库类
 * 使用Room框架管理SQLite数据库，包含所有占卜相关的数据表
 * 
 * 数据表说明：
 * - tarot_cards: 78张塔罗牌数据
 * - hexagram_64: 64卦数据  
 * - yao_texts: 384条爻辞数据
 * - lenormand_cards: 36张雷诺曼卡数据
 * - divination_history: 占卜历史记录
 */
@Database(
    entities = {
        TarotCard.class,
        Hexagram.class,
        YaoText.class,
        LenormandCard.class,
        DivinationHistory.class
    },
    version = 1,
    exportSchema = false
)
public abstract class DivinationDatabase extends RoomDatabase {
    
    private static final String DATABASE_NAME = "divination_database";
    private static volatile DivinationDatabase INSTANCE;
    
    // DAO抽象方法声明
    public abstract TarotCardDao tarotCardDao();
    public abstract HexagramDao hexagramDao();
    public abstract YaoTextDao yaoTextDao();
    public abstract LenormandCardDao lenormandCardDao();
    public abstract DivinationHistoryDao divinationHistoryDao();
    
    /**
     * 单例模式获取数据库实例
     * @param context 应用上下文
     * @return 数据库实例
     */
    public static DivinationDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (DivinationDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(
                            context.getApplicationContext(),
                            DivinationDatabase.class,
                            DATABASE_NAME
                        )
                        .addCallback(DATABASE_CALLBACK)
                        .build();
                }
            }
        }
        return INSTANCE;
    }
    
    /**
     * 数据库创建回调
     * 在数据库首次创建时自动初始化预置数据
     */
    private static final RoomDatabase.Callback DATABASE_CALLBACK = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            
            // 在后台线程初始化预置数据
            new Thread(() -> {
                try {
                    if (INSTANCE != null) {
                        DataInitializer.initializePreloadedData(INSTANCE);
                    }
                } catch (Exception e) {
                    // 记录初始化错误，但不影响数据库创建
                    android.util.Log.e("DivinationDatabase", "预置数据初始化失败", e);
                }
            }).start();
        }
        
        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            // 数据库打开时的额外配置
            android.util.Log.d("DivinationDatabase", "数据库已打开");
        }
    };
    
    /**
     * 强制重新创建数据库实例 (用于测试或重置)
     * 警告：这会删除所有数据！
     */
    public static void destroyInstance() {
        if (INSTANCE != null) {
            if (INSTANCE.isOpen()) {
                INSTANCE.close();
            }
            INSTANCE = null;
        }
    }
    
    /**
     * 检查数据库是否已初始化完成
     * @return 是否已初始化
     */
    public boolean isInitialized() {
        try {
            // 检查关键数据表是否有数据
            TarotCardDao tarotDao = tarotCardDao();
            HexagramDao hexagramDao = hexagramDao();
            LenormandCardDao lenormandDao = lenormandCardDao();
            
            return tarotDao.isDataInitialized() &&
                   hexagramDao.isDataInitialized() &&
                   lenormandDao.isDataInitialized();
        } catch (Exception e) {
            android.util.Log.e("DivinationDatabase", "检查初始化状态失败", e);
            return false;
        }
    }
    
    /**
     * 获取数据库统计信息
     * @return 数据库统计信息
     */
    public DatabaseStats getDatabaseStats() {
        try {
            DatabaseStats stats = new DatabaseStats();
            
            TarotCardDao tarotDao = tarotCardDao();
            HexagramDao hexagramDao = hexagramDao();
            YaoTextDao yaoDao = yaoTextDao();
            LenormandCardDao lenormandDao = lenormandCardDao();
            DivinationHistoryDao historyDao = divinationHistoryDao();
            
            stats.tarotCardCount = tarotDao.getCardCount();
            stats.hexagramCount = hexagramDao.getHexagramCount();
            stats.yaoTextCount = yaoDao.getYaoTextCount();
            stats.lenormandCardCount = lenormandDao.getCardCount();
            stats.historyCount = historyDao.getHistoryCount();
            
            return stats;
        } catch (Exception e) {
            android.util.Log.e("DivinationDatabase", "获取统计信息失败", e);
            return new DatabaseStats();
        }
    }
    
    /**
     * 重新初始化预置数据 (清空后重新加载)
     * 警告：这会删除所有预置数据并重新加载！
     */
    public void reinitializeData() {
        new Thread(() -> {
            try {
                // 清空预置数据表 (不删除用户历史)
                tarotCardDao().deleteAll();
                hexagramDao().deleteAll();
                yaoTextDao().deleteAll();
                lenormandCardDao().deleteAll();
                
                // 重新初始化
                DataInitializer.initializePreloadedData(this);
                
                android.util.Log.i("DivinationDatabase", "预置数据重新初始化完成");
            } catch (Exception e) {
                android.util.Log.e("DivinationDatabase", "重新初始化失败", e);
            }
        }).start();
    }
    
    /**
     * 数据库统计信息类
     */
    public static class DatabaseStats {
        public int tarotCardCount = 0;
        public int hexagramCount = 0;
        public int yaoTextCount = 0;
        public int lenormandCardCount = 0;
        public int historyCount = 0;
        
        public boolean isFullyInitialized() {
            return tarotCardCount >= 78 &&      // 78张塔罗牌
                   hexagramCount >= 64 &&       // 64卦
                   yaoTextCount >= 384 &&       // 384条爻辞
                   lenormandCardCount >= 36;    // 36张雷诺曼卡
        }
        
        public String getInitializationStatus() {
            if (isFullyInitialized()) {
                return "完全初始化";
            } else {
                StringBuilder status = new StringBuilder("初始化不完整: ");
                if (tarotCardCount < 78) status.append("塔罗牌缺失 ");
                if (hexagramCount < 64) status.append("卦象缺失 ");
                if (yaoTextCount < 384) status.append("爻辞缺失 ");
                if (lenormandCardCount < 36) status.append("雷诺曼卡缺失 ");
                return status.toString();
            }
        }
        
        @Override
        public String toString() {
            return "DatabaseStats{" +
                    "塔罗牌=" + tarotCardCount + "/78, " +
                    "卦象=" + hexagramCount + "/64, " +
                    "爻辞=" + yaoTextCount + "/384, " +
                    "雷诺曼=" + lenormandCardCount + "/36, " +
                    "历史=" + historyCount +
                    '}';
        }
    }
}
